package com.ck.chuangke.controller;

import com.ck.chuangke.service.CkDeviceInfoService;
import com.ck.chuangke.service.CkDeviceModelService;
import com.ck.chuangke.service.CkUpgradeService;
import com.ck.constant.BusinessConstant;
import com.ck.constant.ResponseConstant;
import com.ck.core.BaseController;
import com.ck.exception.ControllerException;
import com.ck.model.chuangke.dto.CkDeviceModelDTO;
import com.ck.model.chuangke.vo.CkDeviceUpgradeListVO;
import com.ck.model.chuangke.vo.CkDeviceUpgradeVO;
import com.ck.model.chuangke.vo.CkUpgradeDeviceListVO;
import com.ck.model.common.DeviceUpgrade;
import com.ck.model.common.User;
import com.ck.model.common.page.PageInfo;
import com.ck.model.common.sys.JsonResponse;
import com.ck.util.HttpUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 
 * <p>Title: CkFirmwareUpgradeController</p>  
 * <p>Description: 固件升级</p>  
 * @author huangf 
 * @date 2018年7月16日
 */
@Controller
@RequestMapping(value = "/firmware")
public class CkFirmwareUpgradeController extends BaseController{
	private static Logger logger = LoggerFactory.getLogger(CkFirmwareUpgradeController.class);
	@Autowired
	private CkUpgradeService deviceUpgradeService;
	@Autowired
	private CkDeviceModelService deviceModelService;
	@Autowired
	private CkDeviceInfoService deviceInfoService;
	/**
	 * 跳转至新增固件界面
	 * @return
	 */
	@RequestMapping(value = "/goAddFirmware")
	public String goAddFirm(Model model){
		List<CkDeviceModelDTO> deviceModelList = deviceModelService.listDeviceModels();
		model.addAttribute("deviceModelList", deviceModelList);
		return "ck/ck_firmware_upgrade_add";
	}

	/**
	 * 保存终端升级信息
	 */
	@ResponseBody
	@RequestMapping(value = "/saveFirmware")
	public Object saveFirmware(DeviceUpgrade deviceUpgrade, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		//验证参数
		if (deviceUpgrade == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		//验证参数
		if (StringUtils.isBlank(deviceUpgrade.getUpgradeName()) || StringUtils.isBlank(deviceUpgrade.getModelName())
				|| StringUtils.isBlank(deviceUpgrade.getUrl())) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "参数不能为空");
		}
		try {
			deviceUpgrade.setUpgradeType(BusinessConstant.DEVICE_UPGRADE_TYPE_FIRMWARE);
			deviceUpgradeService.saveDeviceUpgrade(deviceUpgrade, user, HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CkFirmwareUpgradeController save 保存终端升级信息失败：" + e.getMessage(),e);
			return new JsonResponse(ResponseConstant.CODE_FAIL,"保存终端升级信息失败");
		}
		return "";
	}

	/**
	 * 获取固件列表
	 */
	@RequestMapping(value = "/list")
	public String firmList(Model modelView, Integer pageNum, Integer pageSize) {
		try {
			PageInfo<CkDeviceUpgradeListVO> pageInfo = deviceUpgradeService.listDeviceUpgradeByPage(BusinessConstant.DEVICE_UPGRADE_TYPE_FIRMWARE, pageNum, pageSize);
			modelView.addAttribute("firmList", pageInfo.getList());
			modelView.addAttribute("total", pageInfo.getTotal());
			modelView.addAttribute("pageNum", pageInfo.getPageNum());
			modelView.addAttribute("pageSize", pageInfo.getPageSize());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CkFirmwareUpgradeController firmList 获取固件列表失败：" + e.getMessage(),e);
		}
		return "ck/ck_firmware_upgrade_list";
	}

	/**
	 *  跳转至升级固件
	 */
	@RequestMapping(value = "/goUpgradeFirmware")
	public Object goUpgradeFirm(HttpServletRequest request,Long deviceUpgradeId, Model model) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if (deviceUpgradeId == null) {
			logger.error("CkFirmwareUpgradeController goUpgradeFirm 参数deviceUpgradeId为空，请联系管理员" );
		}
		try {
			//机型
			List<CkDeviceModelDTO> deviceModelList = deviceModelService.listDeviceModels();
			model.addAttribute("deviceModelList", deviceModelList);
			CkDeviceUpgradeVO deviceUpgradeVO = deviceUpgradeService.getDeviceUpgradeByIdVo(deviceUpgradeId);
			model.addAttribute("deviceUpgrade", deviceUpgradeVO);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CkFirmwareUpgradeController goUpgradeFirm 升级固件：" + e.getMessage(),e);
		}
		return "ck/ck_firmware_upgrade_update";
	}


	/**
	 * 升级固件
	 */
	@ResponseBody
	@RequestMapping(value = "/upgradeFirmware", method = RequestMethod.POST)
	public Object upgradeFirm(DeviceUpgrade deviceUpgrade,  HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		Long deviceUpgradeId = deviceUpgrade.getDeviceUpgradeId();
		if (deviceUpgradeId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "升级ID为空，请联系管理员");
		}
		try {
			deviceUpgradeService.updateDeviceUpgrade(deviceUpgrade, user,HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CkFirmwareUpgradeController upgradeFirm升级固件：" + e.getMessage(),e);
			return e;
		}
		return "";

	}
	/**
	 *  固件-终端列表信息
	 */
	@RequestMapping(value = "/firmDeviceList")
	public String firmDeviceList(Long deviceUpgradeId,String firmVer, Integer deviceStatus, String modelName, String province,String city, String area,
	                             String companyName, Integer pageNum, Integer pageSize, Model modelView) {
		// 放入model，用户数据回显
		modelView.addAttribute("deviceUpgradeId", deviceUpgradeId);
		modelView.addAttribute("firmVer", firmVer);
		modelView.addAttribute("deviceStatus", deviceStatus);
		modelView.addAttribute("modelName", modelName);
		modelView.addAttribute("province", province);
		modelView.addAttribute("city", city);
		modelView.addAttribute("area", area);
		modelView.addAttribute("companyName", companyName);

		// mips版本号
		List<String> versionNameList = deviceInfoService.listAllFirmwareVersion();
		modelView.addAttribute("versionNameList", versionNameList);
		// 在线状态
		Map<Object, Object> deviceStatusMap = Maps.newHashMap();
		deviceStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_ON_LINE, "在线");
		deviceStatusMap.put(BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE, "离线");
		modelView.addAttribute("deviceStatusMap", deviceStatusMap);
		
		// 机型
		List<CkDeviceModelDTO> deviceModelList = deviceModelService.listDeviceModelsSelectedUpgrade(deviceUpgradeId);
		modelView.addAttribute("deviceModelList", deviceModelList);

		if(StringUtils.isNotBlank(firmVer)){
			firmVer = firmVer.replace("*", " ");
		}
		// 固件-终端信息
		PageInfo<CkUpgradeDeviceListVO> pageInfo = deviceInfoService.listUpgradeDeviceByPage(null,firmVer, deviceStatus, modelName, province, city, area, companyName, pageNum, pageSize);
		modelView.addAttribute("firmDeviceList", pageInfo.getList());
		modelView.addAttribute("total", pageInfo.getTotal());
		modelView.addAttribute("pageNum", pageInfo.getPageNum());
		modelView.addAttribute("pageSize", pageInfo.getPageSize());
		
		// 汇总在线、离线终端总数 
		if ( null == deviceStatus ) {
			Long onlineCount = deviceInfoService.getDeviceCountByCondition(null, firmVer, BusinessConstant.DEVICE_INFO_STATUS_ON_LINE, modelName, province, city, area, companyName);
			modelView.addAttribute("onlineCount", onlineCount);
			modelView.addAttribute("offlineCount",pageInfo.getTotal() - onlineCount);
		} else if (BusinessConstant.DEVICE_INFO_STATUS_ON_LINE == deviceStatus) {
			modelView.addAttribute("onlineCount", pageInfo.getTotal());
			modelView.addAttribute("offlineCount",0);
		} else if ( BusinessConstant.DEVICE_INFO_STATUS_OFF_LINE == deviceStatus ) {
			modelView.addAttribute("onlineCount", 0);
			modelView.addAttribute("offlineCount",pageInfo.getTotal());
		}
		return "ck/ck_firmware_upgrade_device_list";
	}

	/**
	 * 更新固件
	 */
	@ResponseBody
	@RequestMapping(value = "/updateFirmware")
	public Object updateFirm(String deviceCodes, Long deviceUpgradeId, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
		if (StringUtils.isBlank(deviceCodes)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"请选择终端");
		}
		if (deviceUpgradeId == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL,"升级ID为空，请联系管理员");
		}
		try { 
			deviceInfoService.deviceUpgrade(BusinessConstant.DEVICE_UPGRADE_TYPE_FIRMWARE,deviceCodes, deviceUpgradeId, user,HttpUtils.getRemortIP(request));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("CkFirmwareUpgradeController updateFirm 更新固件失败：" + e.getMessage(),e);
			return new JsonResponse(ResponseConstant.CODE_FAIL,"更新固件失败");
		}
		return "";
	}
	
	/**
	 * 固件文件上传
	 */
	@ResponseBody
	@RequestMapping(value = "/upload/firmware", method = RequestMethod.POST)
	public Object uploadFile(@RequestParam("files") MultipartFile files) {
		if (files == null) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "上传文件不能为空");
		} else if (files.getSize() <= 0) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "文件内容不能为空");
		}
		String fileName = files.getOriginalFilename();
		if (StringUtils.isBlank(fileName)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "文件名不能为空");
		}
		if (!fileName.endsWith(BusinessConstant.FILE_SUFFIX_ZIP)) {
			return new JsonResponse(ResponseConstant.CODE_FAIL, "文件格式不对！");
		}
		try {
			List<Map<Object,Object>> msgList = Lists.newArrayList();
			Map<Object, Object> msgMap = deviceUpgradeService.saveFirmwareFile(files);
			msgList.add(msgMap);
			return msgList;
		} catch (IOException e) {
			e.printStackTrace();
			logger.error("CkFirmwareUpgradeController uploadFile 固件上传文件失败：" + e.getMessage(),e);
			return new ControllerException("固件上传文件失败");
		}
	}
}
